package org.unicorn.android.base

import android.util.Log
import androidx.lifecycle.viewModelScope
import org.unicorn.android.base.net.HttpError
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 *
 * @author     : liujianyou
 * @date : 2022/02/16 18:08
 * @Description:
 */

fun BaseViewModel.network(call: suspend CoroutineScope.() -> Unit, onError: (code: String, msg: String) -> Unit) {
    viewModelScope.launch(Dispatchers.IO) {
        try {
            call.invoke(viewModelScope)
        } catch (e: HttpError) {
            when (e.code) {
                Parameter.NOTLOGIN -> {
//                    putSp(Parameter.TOKEN, "")
                }
                "404", "500" -> {
                    toast("系统错误")
                }
                else -> toast(e.message)
            }
            hideLoading()
            withContext(Dispatchers.Main) {
                onError.invoke(e.code, e.message)
            }
        } catch (e: UnknownHostException) {
            toast("网络异常")
            hideLoading()
        } catch (e: SocketTimeoutException) {
            toast("网络超时")
            hideLoading()
        } catch (e: Exception) {
            Log.d("BuildF", "network: $e")
            toast("请求失败")
            hideLoading()
        }
    }
}